<template>
  <a-spin tip="Loading..." :spinning="spinning">
    <div class="operation-box">
      <a-form :form="form" @submit="handleSubmit">
        <a-form-item label="房屋朝向" v-bind="col">
          <a-input placeholder="请输入房屋朝向" v-decorator="['direction',{initialValue:''}]"/>
        </a-form-item>
        <!-- <a-form-item label="是否交房" v-bind="col">
          <a-select placeholder="请选择是否交房" :options="[{value:0,label:'未交'},{value:1,label:'已交'}]" v-decorator="['over_house']"/>
        </a-form-item> -->
        <a-form-item label="交房时间" v-bind="col">
          <a-date-picker style="width:100%;" placeholder="请选择交房时间" v-decorator="['time']" />
        </a-form-item>
        <a-form-item label="产权年限" v-bind="col">
          <a-input placeholder="请输入产权年限" addonAfter="年" v-decorator="['years',{initialValue:70}]"/>
        </a-form-item>
        <a-form-item label="附件" v-bind="col" extra="最多可上传5张图片，且图片大小不可超过2M。">
          <a-upload class="operation-file-uploader" name="file" accept="image/*" listType="picture-card" :action="baseURL + 'community/uploadPic?token=' + token" @preview="imgPreview" v-decorator="['imgs',{initialValue:[],valuePropName:'fileList',getValueFromEvent:imageUpload}]">
            <div v-if="typeof form.getFieldValue('imgs') === 'undefined' || form.getFieldValue('imgs').length < 5">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
          <a-modal :visible="imagePreviewVisible" :footer="null" @cancel="() => { imagePreviewVisible = false }">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>
        <a-form-item label="备注" v-bind="col">
          <a-input placeholder="请输入备注" v-decorator="['remarks']"/>
        </a-form-item>
        <a-form-item :wrapperCol="{xs:{span:24,offset:0},sm:{span:24,offset:8}}">
          <a-button type="primary" html-type="submit">保存</a-button>
          <a-button style="margin-left: 16px;" @click="() => { $router.go(-1) }">返回</a-button>
        </a-form-item>
      </a-form>
    </div>
  </a-spin>
</template>

<script>
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import moment from 'moment'
  export default {
    name: 'data_houses_extend',
    data() {
      return {
        token:this.$ls.get(ACCESS_TOKEN), // 用户token
        baseURL:this.axios.defaults.baseURL,
        spinning:false,
        form:this.$form.createForm(this),
        col:{
          labelCol:{xs:{span:24},sm:{span:8}},
          wrapperCol:{xs:{span:24},sm:{span:8}}
        },
        logo_fileList:[], // 附件
        previewImage:'', // 图片预览
        imagePreviewVisible:false,
        id:'', // 房屋id
      }
    },
    async mounted() {
      let { id } = this.$route.params;
      this.id = id;
      if(!isNaN(this.id) && !this.$common.isEmpty(id)){
        let { direction,over_house,time,years,imgs,remarks } = await this.getInfo(id);
        this.form.setFieldsValue({direction,over_house,time,years,imgs,remarks});
      }else this.$router.go(-1);
    },
    methods:{
      // 获取小区设置信息
      getInfo(id) {
        return new Promise((resolve,reject) => {
          this.axios({
            method:'post',
            url:'/houses/getHousesInfo',
            data:{id,token:this.token}
          }).then(res => {
            let { code,msg,data } = res;
            if(code === 0){
              data.time = this.$common.isEmpty(data.time) ? undefined : moment(data.time);
              for(let item of data.imgs) item.url = this.baseURL + 'static/uploads/' + item.url;
              resolve(data);
            }else this.$message.warning(msg);
          }).catch(err => {
            this.$message.error('服务器发生错误...');
          })
        })
      },
      // 提交信息
      handleSubmit(e) {
        e.preventDefault();
        this.form.validateFields((err, values) => {
          if (err) {
            for(let key in err){
              for(let item of err[key]['errors']) return this.$message.warning(item['message'],2);
            }
          }
          Object.assign(values,{token:this.token,id:this.id,imgs:values.imgs.map(item => item.uid).join(','),time:this.$common.isEmpty(values.time) ? '' : values.time.format('YYYY-MM-DD'),send:''});
          this.spinning = true;
          this.axios({
            method:'post',
            url:'/houses/operation',
            data:values,
          }).then(res => {
            this.spinning = false;
            if(res.code == 0){
              this.$message.success('保存成功',1);
              this.$router.go(-2);
              // this.$router.push({name:'data_houses_index'})
            }else this.$message.warning(res.msg);
          }).catch(() => {this.$message.error('服务器发生错误...',2),this.spinning = false;});
        });
      },
      // 上传图片
      imageUpload({file,fileList}) {
        let imgs = this.form.getFieldValue('imgs');
        console.log(imgs);
        if((file.size / 1024 / 1024) > 2) {
          this.$message.warning('图片最大不可超过2M',2);
          return imgs;
        }
        if(file.status === 'removed') {
          for(let [index,item] of imgs.entries()){
            if(item.status === 'removed') imgs.splice(index,1)
          }
          return imgs;
        }
        if(file.status === 'uploading') return fileList;
        if(file.status === 'done'){
          let { code,msg,data } = file.response;
          if(code === 0){
            this.$message.success(msg,1);
            for(let [index,item] of imgs.entries()){
              if(item.uid === file.uid){
                imgs[index] = {uid:data.id,name:data.file_name,url:this.baseURL+'static/uploads/'+data.url}
              }
            }
            return imgs;
          }else {
            this.$message.error(msg,1);
            return imgs;
          }
        }
        if(file.status === 'error'){
          this.$message.error('上传失败',1);
          return imgs;
        }
      },
      // 图片预览
      imgPreview(info) {
        this.previewImage = info.url || info.thumbUrl
        this.imagePreviewVisible = true
      }
    }
  }
</script>

<style>

</style>
<style lang="less" scoped>
  .operation-box{
    background: #ffffff;
    padding:25px;
    box-sizing: border-box;
    .ant-upload-select-picture-card i {
      font-size: 32px;
      color: #999;
    }
    .ant-upload-select-picture-card .ant-upload-text {
      margin-top: 8px;
      color: #666;
    }
  }
</style>